package com.gz.utils;


import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class AddressLngLatExchange {

    public String getLngLat(String address) {
        StringBuffer json = new StringBuffer();
//        String key="7f4ffae4074e8b8e4d147190527a4b72";
        String key="47fa3bcc499016104283079c04177447";
        try {
            URL u = new URL("http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key="+key);
            URLConnection yc = u.openConnection();
            //读取返回的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputline = null;
            while ((inputline = in.readLine()) != null) {
                json.append(inputline);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String jsonStr = json.toString();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);

        if (jsonObject.getJSONArray("geocodes").size() > 0){

            return jsonObject.getJSONArray("geocodes").getJSONObject(0).get("location").toString();
        }
        else{
            return null;
        }
    }

    public static void main(String[] args) {
        AddressLngLatExchange addressLngLatExchange = new AddressLngLatExchange();
        System.out.println(addressLngLatExchange.getLngLat("光明D9空间"));

    }
}

